import 'dart:typed_data';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:get/get.dart';
import 'package:projectfluttershengyihuatong/category/catetory_controller.dart';
import 'package:projectfluttershengyihuatong/courseDetail/coursedetail.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'package:projectfluttershengyihuatong/tab1/HomeModel.dart';
import 'package:projectfluttershengyihuatong/tab1/homeviewmodel.dart';
import 'package:projectfluttershengyihuatong/tool/public_color.dart';
import 'package:projectfluttershengyihuatong/tool/tool.dart';
import 'package:projectfluttershengyihuatong/route.dart';
import 'customview.dart';

void paint(Canvas canvas, Size size) {
  Paint _paint = Paint();
  canvas.drawPoints(PointMode.points,
      [Offset(0, 0), Offset(30, 0), Offset(60, 0), Offset(90, 0)], _paint);

  _paint.strokeCap = StrokeCap.round;
  canvas.drawPoints(PointMode.points,
      [Offset(0, 50), Offset(30, 50), Offset(60, 50), Offset(90, 50)], _paint);

  canvas.drawPoints(
      PointMode.lines,
      [Offset(0, 100), Offset(30, 100), Offset(60, 100), Offset(90, 100)],
      _paint);

  canvas.drawPoints(
      PointMode.polygon,
      [Offset(0, 150), Offset(30, 150), Offset(60, 150), Offset(90, 150)],
      _paint);

  Float32List points =
      Float32List.fromList([0, 200, 30, 200, 60, 200, 90, 200]);
  canvas.drawRawPoints(PointMode.points, points, _paint);
}

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    // TODO: implement initState
    viewModel.request();
    super.initState();
  }




  var viewModel = HomeViewModel();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(44),
        child: AppBar(
          backgroundColor: primaryColor,
          leading: CategoryBtn(voidCallback: (){
            viewModel.request();
          },),
          leadingWidth: 200.adapt(),
        ),
      ),
      body: Container(
        child: StreamBuilder(
          stream: viewModel.streamController.stream,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              if (snapshot.data == null) return Container();
              final model = snapshot.data!;
              final banner = model.banner?.indexPageTop ?? [];
              final navigation = model.indexPage?.navigation ?? [];
              final singleImg = model.singleImg;
              final recoment = model.indexPage?.recommendCourse ?? [];
              final hot = model.indexPage?.hotKe ?? [];
              final company = model.indexPage?.company ?? [];

              return CustomScrollView(
                slivers: [
                  HomeBanner(banner: banner),
                  HomeNavigation(navigation: navigation),
                  SingleModule(singleImg: singleImg),
                  HomeHeader(
                    title: "推荐课程",
                    list: recoment,
                    moreActionBlock: () {
                      // TODO: 跳转到更多
                    },
                  ),
                  RecommentModule(recoment: recoment.map((e){
                    final model = ShowModel(e.title ?? "", e.cover ?? "");
                    return model;
                  }).toList(),block: (index){
                    final model = recoment[index];
                    Get.toNamed(RouteNames.COURSEDETAIL,arguments: {"courseId": model.id ?? ""});

                  },),
                  HomeHeader(list: hot, title: "热门课程", moreActionBlock: (){
                    //TODO: 热门课程更多
                  }),
                  RecommentModule(
                      recoment: hot
                          .map((e) => ShowModel(e.title ?? "", e.cover ?? ""))
                          .toList(), block: (index){

                  },),

                  HomeHeader(list: company, title: "企业课程", moreActionBlock: (){
                    //TODO: 热门课程更多
                  }),
                  RecommentModule(
                      recoment: company
                          .map((e) => ShowModel(e.title ?? "", e.img ?? ""))
                          .toList(), block: (index){

                  },),

                ],
              );
            }
            return const Center(child: CircularProgressIndicator());
          },
        ),
      ),
    );
  }
}

class RecommentModule extends StatelessWidget {
  const RecommentModule({
    super.key,
    required this.recoment,
    required this.block,
  });
  final ValueChanged<int> block;

  final List<ShowModel> recoment;

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.only(left: 8, right: 8),
      sliver: SliverGrid(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            final model = recoment[index];
            final img = model.imageUrl ?? "";
            final title = model.title ?? "";
            return GestureDetector(
              onTap: (){
                block(index);
              },
              child: Container(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    AspectRatio(
                      aspectRatio: 1.8,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(6),
                          child: Image.network(
                        img,
                        fit: BoxFit.fill,
                      )),
                    ),
                    const SizedBox(height: 5,),
                    Expanded(child: Text(title)),
                  ],
                ),
              ),
            );
          },
          childCount: recoment.length,
        ),
        gridDelegate:
            const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                crossAxisSpacing: 8,
                childAspectRatio: 1.4),
      ),
    );
  }
}

class HomeHeader extends StatelessWidget {
  const HomeHeader(
      {super.key,
      required this.list,
      required this.title,
      required this.moreActionBlock});

  final String title;
  final VoidCallback moreActionBlock;
  final List list;

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: const EdgeInsets.only(left: 8, right: 8),
      sliver: SliverGrid(
          delegate: SliverChildListDelegate(
            [
              list.isEmpty
                  ? Container()
                  : Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            title,
                            style: TextStyle(
                                color: color33,
                                fontSize: 18.adapt(),
                                fontWeight: FontWeight.bold),
                          ),
                          IconButton(
                            onPressed: moreActionBlock,
                            icon: Row(
                              children: [
                                Text(
                                  "更多",
                                  style: TextStyle(
                                    color: color66,
                                    fontSize: 13,
                                  ),
                                ),
                                const SizedBox(
                                  width: 3,
                                ),
                                Image.asset(
                                  assetImage("ico_arrow_right"),
                                  width: 10,
                                  height: 10,
                                ),
                              ],
                            ),
                            color: Colors.red,
                          ),
                        ],
                      ),
                    ),
            ],
          ),
          gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
            maxCrossAxisExtent: double.infinity,
            mainAxisExtent: list.isEmpty ? 1 : 44,
          )),
    );
  }
}

class SingleModule extends StatelessWidget {
  const SingleModule({
    super.key,
    required this.singleImg,
  });

  final SingleImg? singleImg;

  @override
  Widget build(BuildContext context) {
    return SliverPadding(
      padding: EdgeInsets.fromLTRB(8, 10, 8, 10),
      sliver: SliverGrid(
          delegate: SliverChildBuilderDelegate((context, index) {
            return Container(
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  AspectRatio(
                      aspectRatio: 0.8,
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(6),
                        child: Image.network(
                          singleImg?.indexPageHot?.img ?? "",
                          fit: BoxFit.fill,
                        ),
                      )),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.stretch,
                      children: [
                        Expanded(
                            child: ClipRRect(
                          borderRadius: BorderRadius.circular(6),
                          child: Image.network(
                            singleImg?.indexPageHotUp?.img ?? "",
                            fit: BoxFit.fill,
                          ),
                        )),
                        const SizedBox(
                          height: 10,
                        ),
                        Expanded(
                            child: ClipRRect(
                                borderRadius: BorderRadius.circular(6),
                                child: Image.network(
                                  singleImg?.indexPageHotDown?.img ?? "",
                                  fit: BoxFit.fill,
                                )))
                      ],
                    ),
                  ),
                ],
              ),
            );
          }, childCount: 1),
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 1, childAspectRatio: 1.8)),
    );
  }
}

class HomeNavigation extends StatelessWidget {
  const HomeNavigation({
    super.key,
    required this.navigation,
  });

  final List<Navigation> navigation;

  @override
  Widget build(BuildContext context) {
    return SliverGrid(
        delegate: SliverChildBuilderDelegate(
          (context, index) {
            final item = navigation[index];

            return GestureDetector(
              onTap: () {},
              child: Container(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Image.network(
                      item.icon ?? "",
                      width: 30,
                      height: 30,
                    ),
                    Text(item.title ?? "")
                  ],
                ),
              ),
            );
          },
          childCount: navigation.length,
        ),
        gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 4, crossAxisSpacing: 10, childAspectRatio: 1.5));
  }
}

class HomeBanner extends StatelessWidget {
  const HomeBanner({
    super.key,
    required this.banner,
  });

  final List<IndexPageTop> banner;

  @override
  Widget build(BuildContext context) {
    return SliverGrid(
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 1,
        childAspectRatio: 1.75,
      ),
      delegate: SliverChildBuilderDelegate((context, index) {
        final bannerModel = banner[index];
        return Container(
          child: Stack(
            children: [
              Container(
                constraints: const BoxConstraints.expand(),
                child: CustomPaint(
                  painter: _HomeCustomPainter(),
                ),
              ),
              Positioned(
                left: 8,
                right: 8,
                top: 10,
                bottom: 10,
                child: PhysicalModel(
                  color: Colors.transparent,
                  borderRadius: BorderRadius.circular(12),
                  clipBehavior: Clip.antiAlias,
                  child: Swiper(
                    itemBuilder: (context, index) {
                      return ConstrainedBox(
                        constraints: const BoxConstraints.expand(),
                        child: Image.network(
                          bannerModel.img ?? "",
                          fit: BoxFit.fill,
                        ),
                      );
                    },
                    itemCount: banner.length,
                    pagination: SwiperPagination(),
                    // control: SwiperControl(),
                  ),
                ),
              ),
            ],
          ),
        );
      }, childCount: 1),
    );
  }
}

class _HomeCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    Paint paint = Paint();
    paint.color = primaryColor;
    final rect = RRect.fromLTRBR(
        0, -300, size.width, size.height - 40, Radius.circular(12));
    canvas.drawRRect(rect, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return this != oldDelegate;
  }
}
